<?php

namespace app\service;

use app\models\common\SmsLogModel;

class SmsService
{
    private $driver;
    private $logModel;

    function __construct()
    {
        $interface_type = env('SMS_DRIVER', 'AliSms');
        $config = [
            'api_key' => env('SMS_API_KEY', ''),
            'api_secret' => env('SMS_API_SECRET', ''),
            'sms_sign' => env('SMS_SIGN', ''),
            'api_extno' => env('SMS_API_EXTNO', ''),
        ];
        $this->driver = call_user_func_array(array("\\app\\service\\SmsService\\" . $interface_type, 'instance'), [$config]);
        $this->logModel = new SmsLogModel();
    }

    /**
     * 发送短信
     * @param $mobile
     * @param $content
     * @param $logType
     * @param array $param
     * @return array
     */
    public function sendSms($apiKey, array $param = [])
    {
        if (!isset($param['mobile']) or !$param['mobile']) {
            return funReturn(STATUS_CODE_DATAERROR, '缺少手机号');
        }
        if (!checkMobile($param['mobile'])) {
            return funReturn(STATUS_CODE_DATAERROR, '手机号不合法');
        }
        if (!isset($param['content']) or !$param['content']) {
            return funReturn(STATUS_CODE_DATAERROR, '缺少内容');
        }
        $sendRes = $this->driver->sendSingle($param['mobile'], $param['content'], $param);

        $sendStatus = $this->logModel::STATUS_SUCCESS;
        if ($sendRes['status'] != STATUS_CODE_SUCCESS) {
            $sendStatus = $this->logModel::STATUS_FAIL;
        }

        $dataRes = $this->logModel->createRecord([
            'mobile' => $param['mobile'],
            'content' => $param['content'],
            'api_key' => $apiKey,
            'status' => $sendStatus
        ]);
        if ($dataRes['status'] != STATUS_CODE_SUCCESS or $sendRes['status'] != STATUS_CODE_SUCCESS) {
            return funReturn(STATUS_CODE_INSIDEERROR, '发送失败请重试');
        }
        return funReturn(STATUS_CODE_SUCCESS, 'success');
    }

    /**
     * 获取日志模型
     * @return SmsLogModel
     * @date 2021-01-21 14:23
     */
    public function getLogModel()
    {
        return $this->logModel;
    }
}